import 'dart:async';

import 'package:detect/utils/api_util.dart';
import 'package:detect/utils/ws_util.dart';
import 'package:flutter/material.dart';

class StateNotifier extends ChangeNotifier {
  final Completer<String> _completer = Completer<String>();
  late Map<String, dynamic> _state;
  bool _inited = false;

  StateNotifier() {
    ApiUtil().listenStatus().then((value) {
      WSUtil.connect().listener([
        ReceiveMsgListener("event", (response) {
          if (_inited && response['value'] == 512) {
            _state['fpga_state'] = response['param'];
            notifyListeners();
          }
          return false;
        }),
        ReceiveMsgListener("status", (response) {
          Map<String, dynamic> data = response['data'];
          if (!_completer.isCompleted && data['work_state'] == 3) _completer.complete(data['fpga_time']);
          if (_completer.isCompleted) {
            _state = data;
            notifyListeners();
            _inited = true;
          }
          return false;
        }),
      ]);
    });
  }

  Future<String> get initTime => _completer.future;

  Map<String, dynamic> get state => _state;

  int get localId => _state['local_id'];
}
